package com.its.common.gateway.filter;

import com.its.common.gateway.config.IgnoreWhiteProperties;
import com.its.common.constant.CacheConstants;
import com.its.common.constant.HttpStatus;
import com.its.common.constant.TokenConstants;
import com.its.common.util.ServletUtils;
import com.its.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关鉴权
 *
 * @author xiaxp
 */
public abstract class AbsAuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AbsAuthFilter.class);

    /**
     * 排除过滤的 uri 地址，可在nacos中添加
     */
    @Lazy
    @Autowired
    protected IgnoreWhiteProperties ignoreWhite;

    /** 处理认证
     * @param exchange
     * @param chain
     * @return
     */
    public abstract Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }

        return doFilter(exchange, chain);

//        ServerHttpRequest.Builder mutate = request.mutate();

//        String token = getToken(request);
////        if (StringUtils.isEmpty(token)) {
////            return unauthorizedResponse(exchange, "令牌不能为空");
////        }
//
//        token = TokenConstants.TEST_SECRET;
//
//        Object authorizedToken = redissonClient.getBucket(getTokenKey(token)).get();
//        if(null != authorizedToken){
//            //获取token的value为user的信息
//        }else{
//            //TODO 验证
//            //令牌已过期或验证不正确
//            //登录状态已过期
//        }
//
//        String userId = "test";
//        String userName = "test";
//
//        if(TokenConstants.TEST_SECRET.equals(token)){
//            userId = "TEST_SECRET";
//            userName = "TEST_SECRET";
//        }
//
//        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(userName)) {
//            return unauthorizedResponse(exchange, "令牌验证失败");
//        }
//
//        // 设置用户信息到请求
//        addHeader(mutate, SecurityConstants.Details.USER_ID.getCode(), userId);
//        addHeader(mutate, SecurityConstants.Details.USER_NAME.getCode(), userName);
//
//        // 内部请求来源参数清除
//        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
//        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    protected void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    protected void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    protected Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 获取缓存key
     */
    protected String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 获取请求token
     */
    protected String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, StringUtils.EMPTY);
        }
        return token;
    }

    @Override
    public int getOrder() {
        return -200;
    }
}